/* 购物车  */
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useStateStore } from './use.js'
import { shopCartAPI, shopNewCartAPI, deletCartAPI } from '@/apis/shopCart.js'
export const ShopCartStore = defineStore('ShopCart', () => {
    /* 商品 state */
    const cartList = ref([])
    /* 检车是否登录 */
    const useState = useStateStore()
    const tocken = computed(() => useState.userInfo.token)
    /* action */
    const addCart = async (goods) => {
        /* 添加购物车 */
        const { skuId, count } = goods
        // 添加购物车操作
        // 已添加过 - count + 1
        // 没有添加过 - 直接push
        // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
        if (tocken.value) {
            shopCartAPI({ skuId, count })
            const { data: res } = await shopNewCartAPI()
            cartList.value = res.result
        } else {
            const item = cartList.value.find(item => goods.skuId === item.skuId)
            if (item) {
                /* 找到了 */
                item.count += goods.count
            } else {
                cartList.value.push(goods)
            }
        }

    }
    /* 删除商品 */
    const removeCart = async (skuId) => {
        if (tocken.value) {
            const { data: res } = await deletCartAPI([skuId])
            console.log(res.result);
            const { data: re } = await shopNewCartAPI()
            cartList.value = re.result
        } else {
            const idx = cartList.value.findIndex(item => item.skuId === skuId)
            cartList.value.splice(idx, 1)
        }


    }
    /* 清空购物车 */
    const emptyCart = () => {
        cartList.value = []
    }
    // 单选功能
    const singleCheck = (skuId, selected) => {
        // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }
    /* 全选功能 */
    /* 全选 */
    const selectAll = (select) => {
        cartList.value.forEach(item => item.selected = select)
    }
    // 是否全选计算属性
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    return {
        cartList,
        addCart,
        removeCart,
        emptyCart,
        singleCheck,
        selectAll,
        isAll
    }
}, { persist: true })